﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Enm;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxFinishReportController : Controller
    {
        YqdContext ctx;
        DdService ddService;

        public WxFinishReportController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        /// <summary>
        /// 添加交办事项
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult GetList()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;
            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
            }
            var (TableName, KeyName) = SuperviseService.GetTableName(ItemType);
            var state = ctx.Database.SqlQuery<int>("select [Status] from " + TableName + " where " + KeyName + "={0}", ItemID).First();
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            var assign = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == ItemID && it.ItemType == ItemType);
            var AssignID = 0;
            var isReport = 0;
            if (assign != null) { AssignID = assign.AssignID; isReport = assign.IsReport; }
            var report = ctx.Yqd_FinishReport.Where(it => it.ItemID == ItemID && it.ItemType == ItemType);
            var rpt = report.Where(it => it.CheckStatus != 审核状态.退回);
            object FinishReport = null;
            if (rpt.Any())
            {
                var r = rpt.First();
                FinishReport = new
                {
                    r.ReportID,
                    Summary = r.Summary ?? "",
                    Material = !string.IsNullOrWhiteSpace(r.Material) ? JArray.Parse(r.Material) : new JArray(),
                    CheckStatus = r.CheckStatus.ToString(),
                    IsCheck = r.CheckStatus == 审核状态.待审,
                    Reporter = user.FirstOrDefault(m => m.EmployeeCode == r.EmployeeCode)?.Name,
                    Instime = r.Instime.ToString("yyyy-MM-dd HH:mm:ss")
                };
            }
            var l = WxUser.LogonInfo;
            var DeptRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.部门管理员);
            var MsRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.督查人员);
            return this.ToJson(new
            {
                success = true,
                DeptRole,
                MsRole,
                Status = Enum.GetName(typeof(任务状态), state),
                AssignID,
                isReport,
                ShowReportHistory = report.Any(s => s.CheckStatus == 审核状态.退回),
                FinishReport
            });
        }

        /// <summary>
        /// 添加交办事项
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_FinishReport model)
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;
            var IsJb = false;
            string headtitle = "", text = "";
            string AccountId = "";
            if (SuperviseID > 0)
            {
                var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = "领导督导";

                    var user = ctx.Yqd_User.Where(x => x.EmployeeCode == s.EmployeeCode).SingleOrDefault();
                    AccountId = user.AccountId.ToString();
                }
            }
            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
                var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == ItemID);
                if (c != null)
                {
                    headtitle = "领导协调";
                }
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
                var s = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = "精准督查";
                    var user = ctx.Yqd_User.Where(x => x.EmployeeCode == s.EmployeeCode).SingleOrDefault();
                    AccountId = user.AccountId.ToString();
                }
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
                var s = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = s.TaskType.ToString();
                    var user = ctx.Yqd_User.Where(x => x.EmployeeCode == s.EmployeeCode).SingleOrDefault();
                    AccountId = user.AccountId.ToString();
                }

                IsJb = true;
            }
            model.ItemID = ItemID;
            model.ItemType = ItemType;
            model.CheckStatus = 审核状态.待审;
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_FinishReport.Add(model);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                var TaskName = "";
                var tID = model.TaskID;
                if (ItemType == 事项类型.专项交办 || ItemType == 事项类型.专项督查)
                {
                    text = "";
                    var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == model.TaskID);
                    if (t != null) TaskName = t.Name;
                }
                else
                {
                    var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == model.TaskID);
                    if (task != null) TaskName = task.TaskName;
                }
                var l = WxUser.LogonInfo;
                //关闭通知
                var msg = ddService.Notification(new List<string>() { AccountId }, headtitle, tID.ToString(), "任务名称: " + TaskName, $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})填报了办结报告，请及时审核！", true, pushStep: 推送流程.工作流转, unitCode: WxUser.LogonInfo.UnitCode);
                Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了办结报告通知，返回值：" + msg);
                TaskLogService.AddLog(IsJb ? ItemID : model.TaskID, "填写了办结报告", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var l = WxUser.LogonInfo;
            if (!l.Role.Contains(角色类型.管理员))
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "无权限删除"
                });
            }
            var ReportID = Form.GetInt("ReportID");
            var report = ctx.Yqd_FinishReport.FirstOrDefault(it => it.ReportID == ReportID);
            var ret = ctx.Database.ExecuteSql("update Yqd_FinishReport set IsDel=1 where ReportID={0};", ReportID);
            if (ret > 0)
            {
                var IsJb = report.ItemType == 事项类型.专项交办;
                var TaskID = IsJb ? report.ItemID : report.TaskID;
                TaskLogService.AddLog(TaskID, "删除了办结报告", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        /// <summary>
        /// 审核工作方案
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [User]
        public IActionResult Check()
        {
            var ReportID = Form.GetInt("ReportID");
            var m = ctx.Yqd_FinishReport.FirstOrDefault(it => it.ReportID == ReportID);
            var ret = 0;
            if (m != null)
            {
                m.CheckStatus = (审核状态)Form.GetInt("CheckStatus");
                m.ReturnReason = Form.GetString("Reason");
                m.CheckTime = DateTime.Now;
                ret = ctx.SaveChanges();
                if (ret > 0)
                {
                    string headtitle = "", text = "";
                    string employeeName = "";
                    var IsJb = false;
                    List<string> accountId = new List<string>();
                    switch (m.ItemType)
                    {
                        case 事项类型.钉办督导:
                            var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (s != null)
                            {
                                headtitle = "领导督导";

                                var approval = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && it.ItemType == 事项类型.钉办督导).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
                                if (approval != null)
                                {
                                    employeeName = approval.DeptLeader;
                                }
                            }
                            break;
                        case 事项类型.协同管理:
                            var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == m.ItemID);
                            if (c != null)
                            {
                                headtitle = "领导协调";
                                text = "协调内容  " + c.Item;
                            }
                            break;
                        case 事项类型.精准督查:
                            var es = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (es != null)
                            {
                                headtitle = "精准督查";

                                var approval = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && it.ItemType == 事项类型.精准督查).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
                                if (approval != null)
                                {
                                    employeeName = approval.DeptLeader;
                                }
                            }
                            break;
                        case 事项类型.专项交办:
                            var ss = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (ss != null)
                            {
                                headtitle = ss.TaskType.ToString();
                                var approval = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && (it.ItemType == 事项类型.专项交办 || it.ItemType == 事项类型.专项督查)).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
                                if (approval != null)
                                {
                                    employeeName = approval.DeptLeader;
                                }
                            }
                            IsJb = true;
                            break;
                    }
                    var TaskName = "";
                    var tID = m.TaskID;
                    if (m.ItemType == 事项类型.专项交办)
                    {
                        tID = 0;
                        var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == m.TaskID);
                        if (t != null) TaskName = t.Name;
                    }
                    else
                    {
                        var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == m.TaskID);
                        if (task != null) TaskName = task.TaskName;
                    }
                    var l = WxUser.LogonInfo;
                    var assign = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == m.AssignID);
                    //关闭通知
                    if (m.CheckStatus == 审核状态.退回)
                    {
                        var msg = ddService.Notification(accountId, headtitle, tID.ToString(), "任务名称: " + TaskName, $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})退回了办结报告，请重新填报！", pushStep: 推送流程.工作退回, unitCode: assign.LeadUnit, employeeNames: new List<string>() { employeeName });
                        Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了退回办结报告通知，返回值：" + msg);
                    }
                    TaskLogService.AddLog(IsJb ? m.ItemID : m.TaskID, "审核了办结报告(" + m.Summary + ")", IsJb);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult GetHistory()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;

            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
            }
            var data = ctx.Database.SqlQuery<Yqd_FinishReport>("select * from Yqd_FinishReport where [ItemID]={0} and [ItemType]={1} and [CheckStatus]={2} order by [Instime] desc", ItemID, (int)ItemType, (int)审核状态.退回);
            return this.ToJson(new
            {
                success = true,
                totalcount = data.Count(),
                data = data.ToList().Select(it => new
                {
                    it.ReportID,
                    it.Summary,
                    Material = !string.IsNullOrWhiteSpace(it.Material) ? JArray.Parse(it.Material) : new JArray(),
                    it.ReturnReason
                })
            });
        }

        [User]
        public ActionResult Repeal()
        {
            var ReportID = Form.GetInt("ReportID");
            var ret = ctx.Database.ExecuteSql("update Yqd_FinishReport set CheckStatus={1},ReturnReason=null,CheckTime=null where SchemeID={0}", ReportID, (int)审核状态.待审);
            if (ret > 0)
            {
                var p = ctx.Yqd_FinishReport.FirstOrDefault(it => it.ReportID == ReportID);
                var IsJb = p.ItemType == 事项类型.专项交办;
                TaskLogService.AddLog(IsJb ? p.ItemID : p.TaskID, "撤销了办结报告(" + p.Summary + ")", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
